package com.nabi.library.contents.elements.page
{
	public class PageList
	{
		private var m_list:Vector.<IPage>;
		private var m_enableAutoSorting:Boolean;
		
		public function PageList()
		{
			init();
		}
		
		private function init(): void
		{
			m_list = new Vector.<IPage>();
			m_enableAutoSorting = false;
		}
		
		private function isVaildIndex($index:int): Boolean
		{
			var result:Boolean = true;
			if(m_list.length <= $index) result = false;
			
			return result;
		}
		
		public function AddPage($page:IPage): void
		{
			m_list.push($page);
		}
		
		public function AddPageAt($page:IPage, $index:int): void
		{
			if(isVaildIndex($index) == false) throw new Error("Out of range");
			
			var temp:Vector.<IPage> = new Vector.<IPage>(); 
			var i:int;
			for(i = 0; i < m_list.length; ++i)
			{
				if(i == $index) {
					temp.push($page);
				}
				temp.push(m_list[i]);
			}
			
			m_list = new Vector.<IPage>();
			
			for(i = 0; i < temp.length; ++i)
			{
				m_list.push(temp[i]);
			}
			
			temp.length = 0;
			temp = null;
		}
		
		public function RemovePage($page:IPage): void
		{
			var index:int = m_list.indexOf($page);
			if(index < 0) return;
			
			RemovePageAt(index);
		}
		
		public function RemovePageAt($index:int): void
		{
			if(isVaildIndex($index) == false) return;
			
			m_list.splice($index, 1);
		}
		
		public function RenewalPageNumberByIndex(): void
		{
			if(GetTotalPageLength() < 1) return;
			
			for(var i:int = 0; i < m_list.length; ++i)
			{
				var page:IPage = m_list[i];
				page.SetPageNumber(i + 1);
			}
		}
		
		public function SortPagesByPageNumber(): void
		{
			if(GetTotalPageLength() < 1) return;
			
			var page:IPage;
			var temp:Vector.<IPage> = new Vector.<IPage>();
			var pageNumbers:Array = new Array();
			
			for each(page in m_list)
			{
				pageNumbers.push(page.GetPageNumber());
			}
			
			pageNumbers.sort(Array.NUMERIC);
			
			while(temp.length != m_list.length)
			{
				for each(page in m_list)
				{
					if(page.GetPageNumber() == pageNumbers[temp.length]) temp.push(page);
				}
			}
			
			m_list = new Vector.<IPage>();
			
			for each(page in temp)
			{
				m_list.push(page);
			}
			
			temp.length = 0;
			temp = null;
			pageNumbers = null;
		}
		
		public function GetTotalPageLength(): int { return m_list.length; }
		
		public function GetPageByIndex($index:int): IPage
		{
			if(isVaildIndex($index) == false) return null;
			
			return m_list[$index];
		}
		
		public function GetPages(): Vector.<IPage> { return m_list; }
		
		public function IsAutoSorting(): Boolean { return m_enableAutoSorting; }
		
		public function SetAutoSorting($value:Boolean): void { m_enableAutoSorting = $value; }
	}
}